package work.shyk.control;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * description: <br>
 * createTime: 2021/5/27 11:06 <br>
 *
 * @author zzh
 */
public class HttpTest {
    private static Logger logger = LoggerFactory.getLogger(HttpTest.class);

    private static RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(60000)
            .setConnectTimeout(60000)
            .setConnectionRequestTimeout(60000)
            .build();

    private static CloseableHttpClient httpClient;

    static {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                @Override
                public boolean isTrusted(X509Certificate[] xcs, String string){
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", sslConnectionSocketFactory)
                    .build();

            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    registry);
            httpClientConnectionManager.setMaxTotal(100);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory);

            httpClient = httpClientBuilder.setConnectionManager(httpClientConnectionManager).build();
        }
        catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException ex) {
            logger.error(ex.getMessage());
            httpClient = HttpClients.createDefault();
        }
    }

    public static Map<String, String> getstatus(String url) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        Map<String, String> invokeStatusMap = sendHttpsGet(httpClient, httpGet);
        return invokeStatusMap;
    }


    private static Map<String, String> sendHttpsGet(CloseableHttpClient httpClient, HttpGet httpGet) {
        Map<String, String> resultMap = new HashMap<String, String>();
        HttpEntity entity = null;
        String responseContent = null;
        Integer statusCode = null;
        httpGet.setConfig(requestConfig);
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            // 执行请求

            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
            statusCode = response.getStatusLine().getStatusCode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultMap.put("status", statusCode == null ? null : statusCode.toString());
        resultMap.put("body", responseContent == null ? null : responseContent);
        return resultMap;
    }


    public static void main(String[] args) {
        System.out.println(getstatus("https://aaa.platform.promace.pcitc.com/ResourceService/apps/ICC_TCP_NEW/properties/ICC_TCP_NEW_MENU/propertyValues?userCode=admin"));

        System.out.println(getstatus("http://aaa.platform.promace.pcitc.com/ResourceService/apps/ICC_TCP_NEW/properties/ICC_TCP_NEW_MENU/propertyValues?userCode=admin"));
    }
}
